import { create } from 'zustand'
import { persist, devtools } from 'zustand/middleware'
import { immer } from 'zustand/middleware/immer'
import resetters from '@/store/resetters.ts'

type AppStoreType = typeof initState

// 初始数据
const initState = {
  token: '',
  collapsed: false
}

const useAppStore = create<AppStoreType>()(
  immer(
    devtools(
      persist(
        (set) => {
          // 想 resetters 数组中添加重置当前 store 的 reset 函数
          resetters.push(() => set(initState))
          // store 中的数据
          return {
            ...initState
          }
        },
        { name: 'app-store' }
      ),
      { name: 'app-store' }
    )
  )
)

export default useAppStore

// 修改数据的函数
// 为 token 赋值
export const setToken = (token: string) => {
  useAppStore.setState((state) => {
    state.token = token
  })
}

// 修改侧边栏的折叠状态
export const setCollapsed = (collapsed: boolean) => {
  useAppStore.setState((state) => {
    state.collapsed = collapsed
  })
}

// 派生的 selector 数据
export const selectCollapsed = (state: AppStoreType) => state.collapsed
export const selectToken = (state: AppStoreType) => state.token
